package cn.e3mall.search.exception;

import cn.e3mall.search.utils.SendMail;
import cn.e3mall.search.utils.StackTrace;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GlobalExceptionResolver implements HandlerExceptionResolver {
    //获取logger
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionResolver.class);
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, final Exception e) {
        logger.info("进入全局异常处理器");
        logger.debug("测试handler的类型："+o.getClass());
        e.printStackTrace();
        logger.error("系统发生异常",e);
        //发送邮件
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    SendMail.sendEmail("搜索系统出现异常",StackTrace.getStackTrace(e));
                } catch (MessagingException e1) {
                    e1.printStackTrace();
                }
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
        //发送短信
        //展示错误页面
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("message","当前网络出现故障，请稍后重试！");
        //返回逻辑视图
        modelAndView.setViewName("error/exception");
        return modelAndView;
    }
}
